package com.dong.mjblog.service;

import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.Objects;

/**
 * @Author:dxf
 * @Date:2020/12/6-12-06 19:48
 */
@Service
@Slf4j
class BaseService {

    private static String filePath;

    private static String fileUrl;

    public static void setFilePath(String filePath) {
        BaseService.filePath = filePath;
    }

    public static void setFileUrl(String fileUrl) {
        BaseService.fileUrl = fileUrl;
    }

    public static HttpServletRequest getRequest() {
        return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
    }


    /**
     * 获取上传目录的绝对路径
     *
     * @return
     */
    public static String getUploadFilePath() {
        return (new File(filePath)).getAbsolutePath();
    }


    /**
     * 获取当前url
     *
     * @param request
     * @return
     */
    private static String getSiteUrlPath(HttpServletRequest request) {
        //String link=request.getScheme()+"://"+request.getServerName();
        String link = "//" + request.getServerName();//直接使用//www.xxx.com的方式可以兼容http和https
        if (request.getServerPort() != 80)
            link += ":" + request.getServerPort();
        link += request.getContextPath();
        return link;
    }

    /**
     * 获取域名
     *
     * @param request
     * @return
     */
    private static String getDomain(HttpServletRequest request) {
        //String link=request.getScheme()+"://"+request.getServerName();
        String domain = "//" + request.getServerName();//直接使用//www.xxx.com的方式可以兼容http和https
        if (request.getServerPort() != 80)
            domain += ":" + request.getServerPort();
        return domain;
    }

    public static String getSiteUrlPath() {
        return getSiteUrlPath(getRequest());
    }

    public static String getDomainPath() {
        return getDomain(getRequest());
    }

    public static String getUploadUrlPath() {
        return fileUrl;
    }

}
